// ignore_for_file: use_key_in_widget_constructors, library_private_types_in_public_api, prefer_final_fields, deprecated_member_use

import 'package:flutter/material.dart';

// ---------------------------
// 自定义图标类（包含图标字体对应的 Unicode 字符和字体家族）
class MyIcons {
  static const IconData order = IconData(0x10207, fontFamily: 'iconfont');
  static const IconData edit = IconData(0x10208, fontFamily: 'iconfont');
  static const IconData tag = IconData(0x10209, fontFamily: 'iconfont');
  static const IconData location = IconData(0x1020a, fontFamily: 'iconfont');
}

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter 综合演示',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MainSelectionPage(),
    );
  }
}

// ---------------------------
// 主选择页面 - 用户可以选择查看哪个演示
class MainSelectionPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Flutter 综合演示'), centerTitle: true),
      body: Container(
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: [Colors.blue[50]!, Colors.white],
          ),
        ),
        child: Center(
          child: Padding(
            padding: EdgeInsets.all(32),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Icon(Icons.phone_android, size: 80, color: Colors.blue[600]),
                SizedBox(height: 24),
                Text(
                  '选择演示类型',
                  style: TextStyle(
                    fontSize: 28,
                    fontWeight: FontWeight.bold,
                    color: Colors.grey[800],
                  ),
                ),
                SizedBox(height: 16),
                Text(
                  '请选择您想要查看的Flutter组件演示',
                  style: TextStyle(fontSize: 16, color: Colors.grey[600]),
                  textAlign: TextAlign.center,
                ),
                SizedBox(height: 48),

                // 图片和图标演示按钮
                _buildSelectionCard(
                  context,
                  icon: Icons.image,
                  title: '图片及图标演示',
                  subtitle: '展示图片的Fit模式、颜色混合、重复模式和图标使用',
                  color: Colors.purple,
                  onTap:
                      () => Navigator.push(
                        context,
                        MaterialPageRoute(
                          builder: (context) => ImagePropertiesDemo(),
                        ),
                      ),
                ),

                SizedBox(height: 24),

                // 交互组件演示按钮
                _buildSelectionCard(
                  context,
                  icon: Icons.touch_app,
                  title: '交互组件演示',
                  subtitle: '展示单选开关、三态复选框、复选框组和开关组件',
                  color: Colors.green,
                  onTap:
                      () => Navigator.push(
                        context,
                        MaterialPageRoute(
                          builder: (context) => ComponentDemoPage(),
                        ),
                      ),
                ),

                SizedBox(height: 24),
                Text(
                  '点击卡片进入对应演示',
                  style: TextStyle(
                    fontSize: 14,
                    color: Colors.grey[500],
                    fontStyle: FontStyle.italic,
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildSelectionCard(
    BuildContext context, {
    required IconData icon,
    required String title,
    required String subtitle,
    required Color color,
    required VoidCallback onTap,
  }) {
    return Container(
      width: double.infinity,
      constraints: BoxConstraints(maxWidth: 400),
      child: Card(
        elevation: 8,
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
        child: InkWell(
          onTap: onTap,
          borderRadius: BorderRadius.circular(16),
          child: Padding(
            padding: EdgeInsets.all(24),
            child: Row(
              children: [
                Container(
                  padding: EdgeInsets.all(16),
                  decoration: BoxDecoration(
                    color: color.withOpacity(0.1),
                    borderRadius: BorderRadius.circular(12),
                  ),
                  child: Icon(icon, size: 32, color: color),
                ),
                SizedBox(width: 20),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        title,
                        style: TextStyle(
                          fontSize: 18,
                          fontWeight: FontWeight.bold,
                          color: Colors.grey[800],
                        ),
                      ),
                      SizedBox(height: 8),
                      Text(
                        subtitle,
                        style: TextStyle(fontSize: 14, color: Colors.grey[600]),
                      ),
                    ],
                  ),
                ),
                Icon(
                  Icons.arrow_forward_ios,
                  color: Colors.grey[400],
                  size: 20,
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

// ---------------------------
// 图片及图标演示主页面（状态管理页面，包含选项卡切换功能）
class ImagePropertiesDemo extends StatefulWidget {
  @override
  State<ImagePropertiesDemo> createState() => _ImagePropertiesDemoState();
}

class _ImagePropertiesDemoState extends State<ImagePropertiesDemo> {
  int _currentTabIndex = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('图片及图标演示'),
        leading: IconButton(
          icon: Icon(Icons.arrow_back),
          onPressed: () => Navigator.pop(context),
        ),
      ),
      body: Column(
        children: [_buildTabBar(), Expanded(child: _buildTabContent())],
      ),
    );
  }

  /// 构建选项卡导航栏
  Widget _buildTabBar() {
    return Container(
      padding: EdgeInsets.symmetric(vertical: 8, horizontal: 16),
      child: SingleChildScrollView(
        scrollDirection: Axis.horizontal,
        child: Row(
          children: [
            _buildTabButton(0, '图片Fit模式'),
            SizedBox(width: 8),
            _buildTabButton(1, '图片颜色混合'),
            SizedBox(width: 8),
            _buildTabButton(2, '图片重复模式'),
            SizedBox(width: 8),
            _buildTabButton(3, '图标展示'),
          ],
        ),
      ),
    );
  }

  Widget _buildTabButton(int index, String text) {
    return ElevatedButton(
      style: ElevatedButton.styleFrom(
        backgroundColor:
            _currentTabIndex == index ? Colors.blue : Colors.grey[300],
        foregroundColor:
            _currentTabIndex == index ? Colors.white : Colors.grey[700],
        elevation: _currentTabIndex == index ? 4 : 1,
      ),
      onPressed: () => setState(() => _currentTabIndex = index),
      child: Text(text),
    );
  }

  Widget _buildTabContent() {
    switch (_currentTabIndex) {
      case 0:
        return _buildFitTab();
      case 1:
        return _buildColorBlendTab();
      case 2:
        return _buildRepeatTab();
      case 3:
        return _buildIconsTab();
      default:
        return Container();
    }
  }

  // ---------------------------
  // Fit模式演示模块（展示不同图片适配模式效果）
  Widget _buildFitTab() {
    const imagePath = 'assets/imgs/avatar.png';

    // 定义不同 Fit 模式及其说明
    final List<Map<String, dynamic>> fitModes = [
      {'name': 'contain', 'fit': BoxFit.contain, 'desc': '保持宽高比，完整显示图片，可能有黑边'},
      {'name': 'fill', 'fit': BoxFit.fill, 'desc': '拉伸图片填满容器，可能变形'},
      {'name': 'cover', 'fit': BoxFit.cover, 'desc': '保持宽高比填满容器，可能裁剪边缘'},
      {'name': 'fitWidth', 'fit': BoxFit.fitWidth, 'desc': '宽度适配容器，高度按比例缩放'},
      {'name': 'fitHeight', 'fit': BoxFit.fitHeight, 'desc': '高度适配容器，宽度按比例缩放'},
      {'name': 'none', 'fit': BoxFit.none, 'desc': '按原图尺寸显示，可能超出容器'},
    ];

    return ListView.builder(
      padding: EdgeInsets.all(16),
      itemCount: fitModes.length,
      itemBuilder: (context, index) {
        final mode = fitModes[index];
        return Card(
          elevation: 4,
          margin: EdgeInsets.only(bottom: 16),
          child: Container(
            height: 400,
            child: Column(
              children: [
                Expanded(
                  child: Container(
                    width: 800,
                    decoration: BoxDecoration(
                      color: Colors.grey[200],
                      border: Border.all(color: Colors.grey),
                    ),
                    child: Image.asset(
                      imagePath,
                      fit: mode['fit'] as BoxFit,
                      alignment: Alignment.center,
                      errorBuilder: (context, error, stackTrace) {
                        return Container(
                          color: Colors.grey[300],
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Icon(Icons.image, size: 50, color: Colors.grey),
                              Text(
                                '图片加载失败',
                                style: TextStyle(color: Colors.grey),
                              ),
                              Text(
                                '模拟: ${mode['name']}',
                                style: TextStyle(color: Colors.blue),
                              ),
                            ],
                          ),
                        );
                      },
                    ),
                  ),
                ),
                Padding(
                  padding: EdgeInsets.all(12.0),
                  child: Column(
                    children: [
                      Text(
                        mode['name'] as String,
                        style: TextStyle(
                          fontWeight: FontWeight.bold,
                          fontSize: 20,
                        ),
                        textAlign: TextAlign.center,
                      ),
                      SizedBox(height: 4),
                      Text(
                        mode['desc'] as String,
                        style: TextStyle(color: Colors.grey[600], fontSize: 14),
                        textAlign: TextAlign.center,
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  /// 颜色混合模式演示模块（展示图片与颜色的混合效果）- 增加了两种新的混合模式
  Widget _buildColorBlendTab() {
    const imagePath = 'assets/imgs/avatar.png';

    final List<Map<String, dynamic>> blendExamples = [
      {'name': '原图', 'color': null, 'blendMode': null, 'desc': '未应用任何颜色混合'},
      {
        'name': 'difference（差异）',
        'color': Colors.blue,
        'blendMode': BlendMode.difference,
        'desc': '蓝色与图片像素差异混合',
      },
      {
        'name': 'screen（滤色）',
        'color': Colors.yellow,
        'blendMode': BlendMode.screen,
        'desc': '黄色滤色混合，使图片变亮',
      },
      {
        'name': 'multiply（正片叠底）',
        'color': Colors.black54,
        'blendMode': BlendMode.multiply,
        'desc': '黑色正片叠底，使图片变暗',
      },
      // 新增的两种混合模式
      {
        'name': 'overlay（叠加）',
        'color': Colors.purple,
        'blendMode': BlendMode.overlay,
        'desc': '紫色叠加混合，增强对比度',
      },
      {
        'name': 'colorDodge（颜色减淡）',
        'color': Colors.orange,
        'blendMode': BlendMode.colorDodge,
        'desc': '橙色减淡混合，增加亮度',
      },
    ];

    return GridView.builder(
      padding: EdgeInsets.all(16),
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 2,
        crossAxisSpacing: 16,
        mainAxisSpacing: 16,
        childAspectRatio: 1.2,
      ),
      itemCount: blendExamples.length,
      itemBuilder: (context, index) {
        final example = blendExamples[index];
        return Card(
          elevation: 4,
          child: Column(
            children: [
              Expanded(
                child: Container(
                  color: Colors.grey[200],
                  child: Image.asset(
                    imagePath,
                    color: example['color'] as Color?,
                    colorBlendMode: example['blendMode'] as BlendMode?,
                    fit: BoxFit.cover,
                    errorBuilder: (context, error, stackTrace) {
                      return Container(
                        color: example['color'] ?? Colors.grey[300],
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Icon(Icons.image, size: 30, color: Colors.grey),
                            Text(
                              '模拟效果',
                              style: TextStyle(
                                color: Colors.grey,
                                fontSize: 12,
                              ),
                            ),
                          ],
                        ),
                      );
                    },
                  ),
                ),
              ),
              Padding(
                padding: EdgeInsets.all(8.0),
                child: Column(
                  children: [
                    Text(
                      example['name'] as String,
                      style: TextStyle(fontWeight: FontWeight.bold),
                      textAlign: TextAlign.center,
                    ),
                    SizedBox(height: 4),
                    Text(
                      example['desc'] as String,
                      style: TextStyle(color: Colors.grey[600], fontSize: 12),
                      textAlign: TextAlign.center,
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                    ),
                  ],
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  /// 图片重复模式演示模块（展示小图片在容器中的平铺效果）
  Widget _buildRepeatTab() {
    const imagePath = 'assets/imgs/small_icon.png';

    final List<Map<String, dynamic>> repeatModes = [
      {'name': 'noRepeat', 'repeat': ImageRepeat.noRepeat, 'desc': '不重复，仅显示一次'},
      {'name': 'repeatX', 'repeat': ImageRepeat.repeatX, 'desc': '水平方向重复'},
      {'name': 'repeatY', 'repeat': ImageRepeat.repeatY, 'desc': '垂直方向重复'},
      {'name': 'repeat', 'repeat': ImageRepeat.repeat, 'desc': '水平和垂直方向均重复'},
    ];

    return GridView.builder(
      padding: EdgeInsets.all(16),
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 2,
        crossAxisSpacing: 16,
        mainAxisSpacing: 16,
        childAspectRatio: 1.2,
      ),
      itemCount: repeatModes.length,
      itemBuilder: (context, index) {
        final mode = repeatModes[index];
        return Card(
          elevation: 4,
          child: Column(
            children: [
              Expanded(
                child: Container(
                  color: Colors.grey[200],
                  child: Image.asset(
                    imagePath,
                    repeat: mode['repeat'] as ImageRepeat,
                    fit: BoxFit.none,
                    errorBuilder: (context, error, stackTrace) {
                      return Container(
                        color: Colors.grey[300],
                        child: _buildRepeatSimulation(
                          mode['repeat'] as ImageRepeat,
                        ),
                      );
                    },
                  ),
                ),
              ),
              Padding(
                padding: EdgeInsets.all(8.0),
                child: Column(
                  children: [
                    Text(
                      mode['name'] as String,
                      style: TextStyle(fontWeight: FontWeight.bold),
                    ),
                    SizedBox(height: 4),
                    Text(
                      mode['desc'] as String,
                      style: TextStyle(color: Colors.grey[600], fontSize: 12),
                      textAlign: TextAlign.center,
                    ),
                  ],
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  Widget _buildRepeatSimulation(ImageRepeat repeat) {
    Widget iconWidget = Icon(Icons.star, color: Colors.blue, size: 20);

    switch (repeat) {
      case ImageRepeat.noRepeat:
        return Center(child: iconWidget);
      case ImageRepeat.repeatX:
        return Row(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: List.generate(4, (index) => iconWidget),
        );
      case ImageRepeat.repeatY:
        return Column(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: List.generate(4, (index) => iconWidget),
        );
      case ImageRepeat.repeat:
        return GridView.count(
          crossAxisCount: 3,
          children: List.generate(9, (index) => iconWidget),
        );
    }
  }

  /// 图标展示模块（包含系统图标和自定义图标演示）
  Widget _buildIconsTab() {
    return SingleChildScrollView(
      padding: EdgeInsets.all(16),
      child: Column(
        children: [
          // 系统内置图标部分
          Text(
            '内置图标（Material Icons）',
            style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
          ),
          SizedBox(height: 16),
          Wrap(
            spacing: 16,
            runSpacing: 16,
            children: [
              _buildIconDemo(Icons.accessible, Colors.blue, 36, 'accessible'),
              _buildIconDemo(Icons.error, Colors.red, 36, 'error'),
              _buildIconDemo(
                Icons.fingerprint,
                Colors.green,
                48,
                'fingerprint',
              ),
              _buildIconDemo(Icons.star, Colors.yellow[700]!, 48, 'star'),
              _buildIconDemo(
                Icons.heart_broken,
                Colors.pink,
                48,
                'heart_broken',
              ),
              _buildIconDemo(Icons.favorite, Colors.red, 40, 'favorite'),
              _buildIconDemo(Icons.home, Colors.blue, 40, 'home'),
              _buildIconDemo(Icons.settings, Colors.grey, 40, 'settings'),
            ],
          ),
          SizedBox(height: 24),

          Text(
            '自定义图标（iconfont）',
            style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
          ),
          SizedBox(height: 16),
          Wrap(
            spacing: 16,
            runSpacing: 16,
            children: [
              _buildIconDemo(MyIcons.order, Colors.blue, 28, 'order'),
              _buildIconDemo(MyIcons.edit, Colors.green, 38, 'edit'),
              _buildIconDemo(MyIcons.tag, Colors.red, 48, 'tag'),
              _buildIconDemo(MyIcons.location, Colors.orange, 58, 'location'),
            ],
          ),
          SizedBox(height: 24),

          Text(
            '不同尺寸演示',
            style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
          ),
          SizedBox(height: 16),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: [
              _buildIconDemo(Icons.star, Colors.blue, 20, '20px'),
              _buildIconDemo(Icons.star, Colors.blue, 30, '30px'),
              _buildIconDemo(Icons.star, Colors.blue, 40, '40px'),
              _buildIconDemo(Icons.star, Colors.blue, 50, '50px'),
              _buildIconDemo(Icons.star, Colors.blue, 60, '60px'),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildIconDemo(IconData icon, Color color, double size, String label) {
    return Column(
      children: [
        Icon(icon, color: color, size: size),
        SizedBox(height: 4),
        Text(label, style: TextStyle(fontSize: 12, color: Colors.grey[600])),
      ],
    );
  }
}

// ---------------------------
// 交互组件演示页面 - 完善了更多单选和复选框演示
class ComponentDemoPage extends StatefulWidget {
  @override
  _ComponentDemoPageState createState() => _ComponentDemoPageState();
}

class _ComponentDemoPageState extends State<ComponentDemoPage> {
  // 单选开关状态
  int _selectedRadio = 0;
  // 新增的单选组状态
  int _selectedLanguage = 0;
  int _selectedTheme = 0;

  // 三态复选框状态
  bool? _isCheckboxChecked = null;

  // 复选框组状态（多个）
  List<bool> _checkboxGroup = [false, false, false];
  // 新增的复选框组
  List<bool> _featuresGroup = [false, false, false, false];
  List<bool> _permissionsGroup = [false, false, false];

  // Switch状态
  bool _isSwitched = false;
  bool _isNotificationEnabled = false;
  bool _isDarkMode = false;
  bool _isLocationEnabled = true;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('交互组件演示'),
        leading: IconButton(
          icon: Icon(Icons.arrow_back),
          onPressed: () => Navigator.pop(context),
        ),
      ),
      body: SingleChildScrollView(
        padding: EdgeInsets.all(16),
        child: Column(
          children: [
            // 第一个单选开关部分（水果选择）
            Card(
              margin: EdgeInsets.all(12),
              child: Padding(
                padding: EdgeInsets.all(16),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      '单选开关（Radio）- 水果选择',
                      style: TextStyle(
                        fontSize: 18,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    SizedBox(height: 16),
                    Text('请选择最喜欢的水果：'),
                    SizedBox(height: 12),
                    // 循环生成单选选项
                    ...List.generate(
                      3,
                      (index) => RadioListTile<int>(
                        title: Text(_getFruitName(index)),
                        value: index,
                        groupValue: _selectedRadio,
                        onChanged:
                            (value) => setState(() {
                              _selectedRadio = value!;
                            }),
                        activeColor: Colors.green,
                        dense: true,
                      ),
                    ),
                    SizedBox(height: 16),
                    Text(
                      '选中的水果：${_getFruitName(_selectedRadio)}',
                      style: TextStyle(color: Colors.blue, fontSize: 16),
                    ),
                  ],
                ),
              ),
            ),

            // 新增的单选开关部分（编程语言选择）
            Card(
              margin: EdgeInsets.all(12),
              child: Padding(
                padding: EdgeInsets.all(16),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      '单选开关（Radio）- 编程语言选择',
                      style: TextStyle(
                        fontSize: 18,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    SizedBox(height: 16),
                    Text('请选择您最熟悉的编程语言：'),
                    SizedBox(height: 12),
                    ...List.generate(
                      4,
                      (index) => RadioListTile<int>(
                        title: Text(_getLanguageName(index)),
                        subtitle: Text(_getLanguageDescription(index)),
                        value: index,
                        groupValue: _selectedLanguage,
                        onChanged:
                            (value) => setState(() {
                              _selectedLanguage = value!;
                            }),
                        activeColor: Colors.purple,
                        dense: true,
                      ),
                    ),
                    SizedBox(height: 16),
                    Container(
                      padding: EdgeInsets.all(12),
                      decoration: BoxDecoration(
                        color: Colors.purple[50],
                        borderRadius: BorderRadius.circular(8),
                      ),
                      child: Text(
                        '选中的语言：${_getLanguageName(_selectedLanguage)}',
                        style: TextStyle(color: Colors.purple, fontSize: 16),
                      ),
                    ),
                  ],
                ),
              ),
            ),

            // 新增的单选开关部分（主题选择）
            Card(
              margin: EdgeInsets.all(12),
              child: Padding(
                padding: EdgeInsets.all(16),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      '单选开关（Radio）- 主题选择',
                      style: TextStyle(
                        fontSize: 18,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    SizedBox(height: 16),
                    Text('选择应用主题：'),
                    SizedBox(height: 12),
                    Row(
                      children: List.generate(
                        3,
                        (index) => Expanded(
                          child: Container(
                            margin: EdgeInsets.symmetric(horizontal: 4),
                            child: Card(
                              color:
                                  _selectedTheme == index
                                      ? Colors.orange[100]
                                      : Colors.white,
                              child: InkWell(
                                onTap:
                                    () => setState(() {
                                      _selectedTheme = index;
                                    }),
                                borderRadius: BorderRadius.circular(8),
                                child: Padding(
                                  padding: EdgeInsets.all(8),
                                  child: Column(
                                    children: [
                                      Radio<int>(
                                        value: index,
                                        groupValue: _selectedTheme,
                                        onChanged:
                                            (value) => setState(() {
                                              _selectedTheme = value!;
                                            }),
                                        activeColor: Colors.orange,
                                      ),
                                      Icon(
                                        _getThemeIcon(index),
                                        color:
                                            _selectedTheme == index
                                                ? Colors.orange
                                                : Colors.grey,
                                      ),
                                      SizedBox(height: 4),
                                      Text(
                                        _getThemeName(index),
                                        style: TextStyle(
                                          fontSize: 12,
                                          color:
                                              _selectedTheme == index
                                                  ? Colors.orange
                                                  : Colors.grey[600],
                                        ),
                                      ),
                                    ],
                                  ),
                                ),
                              ),
                            ),
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),

            // 三态复选框部分
            Card(
              margin: EdgeInsets.all(12),
              child: Padding(
                padding: EdgeInsets.all(16),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      '三态复选框（Checkbox）',
                      style: TextStyle(
                        fontSize: 18,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    SizedBox(height: 16),

                    // 三态复选框实现
                    Row(
                      children: [
                        Checkbox(
                          value: _isCheckboxChecked,
                          onChanged: (value) {
                            setState(() {
                              // 状态循环：null → true → false → null
                              if (_isCheckboxChecked == null) {
                                _isCheckboxChecked = true;
                              } else if (_isCheckboxChecked == true) {
                                _isCheckboxChecked = false;
                              } else {
                                _isCheckboxChecked = null;
                              }
                            });
                          },
                          tristate: true,
                          fillColor: MaterialStateProperty.all(Colors.blue),
                          checkColor: Colors.white,
                        ),
                        Expanded(child: Text('三态选项 - 点击切换状态')),
                      ],
                    ),

                    SizedBox(height: 16),
                    Container(
                      padding: EdgeInsets.all(12),
                      decoration: BoxDecoration(
                        color: _getCheckboxStateColor(),
                        borderRadius: BorderRadius.circular(8),
                      ),
                      child: Row(
                        children: [
                          Icon(
                            _getCheckboxStateIcon(),
                            color: Colors.white,
                            size: 20,
                          ),
                          SizedBox(width: 8),
                          Text(
                            '当前状态：${_getCheckboxStateText()}',
                            style: TextStyle(color: Colors.white, fontSize: 16),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ),

            // 复选框组部分（兴趣爱好）
            Card(
              margin: EdgeInsets.all(12),
              child: Padding(
                padding: EdgeInsets.all(16),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      '复选框组（Checkbox Group）- 兴趣爱好',
                      style: TextStyle(
                        fontSize: 18,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    SizedBox(height: 16),
                    Text('选择您的兴趣爱好：'),
                    SizedBox(height: 12),

                    // 多选组
                    ...List.generate(
                      3,
                      (index) => CheckboxListTile(
                        title: Text(_getHobbyName(index)),
                        value: _checkboxGroup[index],
                        onChanged:
                            (value) => setState(() {
                              _checkboxGroup[index] = value!;
                            }),
                        controlAffinity: ListTileControlAffinity.leading,
                        activeColor: Colors.purple,
                      ),
                    ),

                    // 全选/取消全选/部分选择的三态控制
                    Divider(),
                    Row(
                      children: [
                        Checkbox(
                          value: _getGroupCheckState(),
                          onChanged: (value) {
                            setState(() {
                              if (_getGroupCheckState() == true) {
                                // 当前全选，切换到全不选
                                _checkboxGroup = List.filled(3, false);
                              } else {
                                // 当前部分选或全不选，切换到全选
                                _checkboxGroup = List.filled(3, true);
                              }
                            });
                          },
                          tristate: true,
                          fillColor: MaterialStateProperty.all(Colors.purple),
                        ),
                        Text('全选/取消全选'),
                        Spacer(),
                        ElevatedButton(
                          onPressed: () {
                            setState(() {
                              _checkboxGroup = List.filled(3, false);
                            });
                          },
                          child: Text('清空选择'),
                          style: ElevatedButton.styleFrom(
                            backgroundColor: Colors.grey[300],
                            foregroundColor: Colors.grey[700],
                          ),
                        ),
                      ],
                    ),

                    SizedBox(height: 16),
                    Container(
                      padding: EdgeInsets.all(12),
                      decoration: BoxDecoration(
                        color: Colors.purple[50],
                        borderRadius: BorderRadius.circular(8),
                      ),
                      child: Text(
                        '选中的爱好：${_getSelectedHobbies()}',
                        style: TextStyle(color: Colors.purple, fontSize: 16),
                      ),
                    ),
                  ],
                ),
              ),
            ),

            // 新增的复选框组（应用功能）
            Card(
              margin: EdgeInsets.all(12),
              child: Padding(
                padding: EdgeInsets.all(16),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      '复选框组（Checkbox Group）- 应用功能',
                      style: TextStyle(
                        fontSize: 18,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    SizedBox(height: 16),
                    Text('选择要启用的应用功能：'),
                    SizedBox(height: 12),

                    ...List.generate(
                      4,
                      (index) => Container(
                        margin: EdgeInsets.symmetric(vertical: 2),
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(8),
                          color:
                              _featuresGroup[index]
                                  ? Colors.green[50]
                                  : Colors.transparent,
                        ),
                        child: CheckboxListTile(
                          title: Text(_getFeatureName(index)),
                          subtitle: Text(_getFeatureDescription(index)),
                          value: _featuresGroup[index],
                          onChanged:
                              (value) => setState(() {
                                _featuresGroup[index] = value!;
                              }),
                          controlAffinity: ListTileControlAffinity.leading,
                          activeColor: Colors.green,
                          secondary: Icon(
                            _getFeatureIcon(index),
                            color:
                                _featuresGroup[index]
                                    ? Colors.green
                                    : Colors.grey,
                          ),
                        ),
                      ),
                    ),

                    SizedBox(height: 16),
                    Row(
                      children: [
                        Expanded(
                          child: ElevatedButton(
                            onPressed: () {
                              setState(() {
                                _featuresGroup = List.filled(4, true);
                              });
                            },
                            child: Text('全部启用'),
                            style: ElevatedButton.styleFrom(
                              backgroundColor: Colors.green,
                              foregroundColor: Colors.white,
                            ),
                          ),
                        ),
                        SizedBox(width: 12),
                        Expanded(
                          child: ElevatedButton(
                            onPressed: () {
                              setState(() {
                                _featuresGroup = List.filled(4, false);
                              });
                            },
                            child: Text('全部禁用'),
                            style: ElevatedButton.styleFrom(
                              backgroundColor: Colors.red,
                              foregroundColor: Colors.white,
                            ),
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ),

            // 新增的复选框组（权限管理）
            Card(
              margin: EdgeInsets.all(12),
              child: Padding(
                padding: EdgeInsets.all(16),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      '复选框组（Checkbox Group）- 权限管理',
                      style: TextStyle(
                        fontSize: 18,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    SizedBox(height: 16),
                    Text('管理应用权限：'),
                    SizedBox(height: 12),

                    ...List.generate(
                      3,
                      (index) => Card(
                        elevation: 2,
                        margin: EdgeInsets.symmetric(vertical: 4),
                        child: CheckboxListTile(
                          title: Text(_getPermissionName(index)),
                          subtitle: Text(_getPermissionDescription(index)),
                          value: _permissionsGroup[index],
                          onChanged:
                              (value) => setState(() {
                                _permissionsGroup[index] = value!;
                              }),
                          controlAffinity: ListTileControlAffinity.trailing,
                          activeColor: Colors.orange,
                          secondary: Container(
                            padding: EdgeInsets.all(8),
                            decoration: BoxDecoration(
                              color:
                                  _permissionsGroup[index]
                                      ? Colors.orange[100]
                                      : Colors.grey[200],
                              borderRadius: BorderRadius.circular(8),
                            ),
                            child: Icon(
                              _getPermissionIcon(index),
                              color:
                                  _permissionsGroup[index]
                                      ? Colors.orange
                                      : Colors.grey,
                            ),
                          ),
                        ),
                      ),
                    ),

                    SizedBox(height: 16),
                    Container(
                      padding: EdgeInsets.all(12),
                      decoration: BoxDecoration(
                        color: Colors.orange[50],
                        borderRadius: BorderRadius.circular(8),
                        border: Border.all(color: Colors.orange[200]!),
                      ),
                      child: Row(
                        children: [
                          Icon(Icons.security, color: Colors.orange),
                          SizedBox(width: 8),
                          Expanded(
                            child: Text(
                              '已授权权限数量：${_permissionsGroup.where((p) => p).length}/3',
                              style: TextStyle(color: Colors.orange[700]),
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ),

            // Switch组件部分（增强版）
            Card(
              margin: EdgeInsets.all(12),
              child: Padding(
                padding: EdgeInsets.all(16),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      '开关组件（Switch）',
                      style: TextStyle(
                        fontSize: 18,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    SizedBox(height: 16),

                    // 基础Switch
                    Row(
                      children: [
                        Switch(
                          value: _isSwitched,
                          onChanged:
                              (value) => setState(() {
                                _isSwitched = value;
                              }),
                          activeColor: Colors.blue,
                          activeTrackColor: Colors.blue[100],
                          inactiveThumbColor: Colors.grey,
                          inactiveTrackColor: Colors.grey[200],
                          thumbColor: MaterialStateProperty.resolveWith(
                            (states) =>
                                states.contains(MaterialState.pressed)
                                    ? Colors.blue[700]
                                    : _isSwitched
                                    ? Colors.white
                                    : null,
                          ),
                        ),
                        SizedBox(width: 16),
                        Expanded(
                          child: Text(
                            _isSwitched ? '夜间模式已开启' : '夜间模式已关闭',
                            style: TextStyle(fontSize: 16),
                          ),
                        ),
                      ],
                    ),

                    SizedBox(height: 16),
                    Divider(),
                    SizedBox(height: 16),

                    Text(
                      '更多开关示例：',
                      style: TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    SizedBox(height: 12),

                    // 通知开关
                    SwitchListTile(
                      title: Text('接收通知'),
                      subtitle: Text('允许应用发送推送通知'),
                      value: _isNotificationEnabled,
                      onChanged:
                          (value) => setState(() {
                            _isNotificationEnabled = value;
                          }),
                      activeColor: Colors.green,
                      secondary: Icon(
                        _isNotificationEnabled
                            ? Icons.notifications_active
                            : Icons.notifications_off,
                        color:
                            _isNotificationEnabled ? Colors.green : Colors.grey,
                      ),
                    ),

                    // 暗黑模式开关
                    SwitchListTile(
                      title: Text('暗黑模式'),
                      subtitle: Text('启用深色主题界面'),
                      value: _isDarkMode,
                      onChanged:
                          (value) => setState(() {
                            _isDarkMode = value;
                          }),
                      activeColor: Colors.indigo,
                      secondary: Icon(
                        _isDarkMode ? Icons.dark_mode : Icons.light_mode,
                        color: _isDarkMode ? Colors.indigo : Colors.grey,
                      ),
                    ),

                    // 位置服务开关
                    Container(
                      decoration: BoxDecoration(
                        color:
                            _isLocationEnabled
                                ? Colors.blue[50]
                                : Colors.red[50],
                        borderRadius: BorderRadius.circular(8),
                      ),
                      child: SwitchListTile(
                        title: Text('位置服务'),
                        subtitle: Text(
                          _isLocationEnabled ? '位置服务已启用' : '位置服务已禁用',
                        ),
                        value: _isLocationEnabled,
                        onChanged:
                            (value) => setState(() {
                              _isLocationEnabled = value;
                            }),
                        activeColor: Colors.blue,
                        secondary: Icon(
                          _isLocationEnabled
                              ? Icons.location_on
                              : Icons.location_off,
                          color: _isLocationEnabled ? Colors.blue : Colors.red,
                        ),
                      ),
                    ),

                    SizedBox(height: 16),

                    // 状态总览
                    Container(
                      padding: EdgeInsets.all(16),
                      decoration: BoxDecoration(
                        color: Colors.grey[100],
                        borderRadius: BorderRadius.circular(12),
                      ),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            '开关状态总览',
                            style: TextStyle(
                              fontWeight: FontWeight.bold,
                              fontSize: 16,
                            ),
                          ),
                          SizedBox(height: 12),
                          _buildStatusItem('夜间模式', _isSwitched),
                          _buildStatusItem('通知', _isNotificationEnabled),
                          _buildStatusItem('暗黑模式', _isDarkMode),
                          _buildStatusItem('位置服务', _isLocationEnabled),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildStatusItem(String title, bool status) {
    return Padding(
      padding: EdgeInsets.symmetric(vertical: 2),
      child: Row(
        children: [
          Icon(
            status ? Icons.check_circle : Icons.cancel,
            color: status ? Colors.green : Colors.red,
            size: 16,
          ),
          SizedBox(width: 8),
          Text(
            '$title: ${status ? "开启" : "关闭"}',
            style: TextStyle(fontSize: 14),
          ),
        ],
      ),
    );
  }

  // 获取三态复选框的文本描述
  String _getCheckboxStateText() {
    if (_isCheckboxChecked == null) return '未确定';
    if (_isCheckboxChecked == true) return '已选中';
    return '未选中';
  }

  // 获取三态复选框的颜色
  Color _getCheckboxStateColor() {
    if (_isCheckboxChecked == null) return Colors.orange;
    if (_isCheckboxChecked == true) return Colors.green;
    return Colors.red;
  }

  // 获取三态复选框的图标
  IconData _getCheckboxStateIcon() {
    if (_isCheckboxChecked == null) return Icons.help;
    if (_isCheckboxChecked == true) return Icons.check;
    return Icons.close;
  }

  // 获取复选框组的整体状态（用于全选控制）
  bool? _getGroupCheckState() {
    final allChecked = _checkboxGroup.every((element) => element);
    final allUnchecked = _checkboxGroup.every((element) => !element);

    if (allChecked) return true;
    if (allUnchecked) return false;
    return null; // 部分选中
  }

  // 辅助方法：获取水果名称
  String _getFruitName(int index) {
    return ['苹果', '香蕉', '橙子'][index];
  }

  // 辅助方法：获取编程语言名称
  String _getLanguageName(int index) {
    return ['Dart/Flutter', 'JavaScript', 'Python', 'Java'][index];
  }

  // 辅助方法：获取编程语言描述
  String _getLanguageDescription(int index) {
    return ['移动应用开发框架', '前端和全栈开发', '数据科学和后端开发', '企业级应用开发'][index];
  }

  // 辅助方法：获取主题名称
  String _getThemeName(int index) {
    return ['浅色', '深色', '自动'][index];
  }

  // 辅助方法：获取主题图标
  IconData _getThemeIcon(int index) {
    return [Icons.light_mode, Icons.dark_mode, Icons.auto_mode][index];
  }

  // 辅助方法：获取爱好名称
  String _getHobbyName(int index) {
    return ['运动', '音乐', '编程'][index];
  }

  // 辅助方法：获取功能名称
  String _getFeatureName(int index) {
    return ['自动同步', '离线模式', '智能推荐', '数据分析'][index];
  }

  // 辅助方法：获取功能描述
  String _getFeatureDescription(int index) {
    return ['自动同步数据到云端', '无网络时可正常使用', '基于AI的内容推荐', '详细的使用数据统计'][index];
  }

  // 辅助方法：获取功能图标
  IconData _getFeatureIcon(int index) {
    return [
      Icons.sync,
      Icons.offline_bolt,
      Icons.psychology,
      Icons.analytics,
    ][index];
  }

  // 辅助方法：获取权限名称
  String _getPermissionName(int index) {
    return ['相机权限', '麦克风权限', '存储权限'][index];
  }

  // 辅助方法：获取权限描述
  String _getPermissionDescription(int index) {
    return ['允许应用使用相机拍照', '允许应用录制音频', '允许应用访问设备存储'][index];
  }

  // 辅助方法：获取权限图标
  IconData _getPermissionIcon(int index) {
    return [Icons.camera_alt, Icons.mic, Icons.storage][index];
  }

  // 辅助方法：获取选中的爱好列表
  String _getSelectedHobbies() {
    List<String> selected = [];
    for (int i = 0; i < _checkboxGroup.length; i++) {
      if (_checkboxGroup[i]) selected.add(_getHobbyName(i));
    }
    return selected.isEmpty ? '无' : selected.join(', ');
  }
}
